package com.zhongli.devplatform.controller.common;

import com.zhongli.devplatform.dto.sys.RoleDTO;
import com.zhongli.devplatform.po.user.ReadRolePO;
import com.zhongli.devplatform.query.sys.RoleQuery;
import com.zhongli.devplatform.service.imp.sys.ReadSecurityMetadataSourceService;
import com.zhongli.devplatform.service.imp.common.ReadMenuService;
import com.zhongli.devplatform.service.imp.sys.ReadRoleService;
import com.zhongli.devplatform.utils.BeanCopierUtil;
import com.zhongli.devplatform.bean.Res;
import com.zhongli.devplatform.vo.sys.RoleVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;


@RestController
@RequestMapping("/role")
public class RoleController {

    @Autowired
    private ReadRoleService roleService;

    @Autowired
    private ReadMenuService menuService;

    @Autowired
    private ReadSecurityMetadataSourceService securityMetadataSourceService;


    @RequestMapping("/list")
    public Res list() {
        List<ReadRolePO> rolePOList = roleService.list();
        List<RoleVO> roleVOList = BeanCopierUtil.copy(rolePOList, RoleVO.class);
        for (RoleVO roleVO : roleVOList) {
            roleVO.setDeviceTypes(roleService.listDeviceType(roleVO.getId()));
        }
        return new Res(roleVOList);
    }

    @PostMapping("/save")
    public Res save(@RequestBody RoleDTO roleDTO) {
        roleService.save(roleDTO);
        return new Res(null);
    }

    @RequestMapping("/delete")
    public Res delete(Integer id) {
        roleService.delete(id);
        return new Res(null);
    }

    @RequestMapping("/isExist")
    public Res isExist(RoleQuery query) {
        return new Res(roleService.isExist(query));
    }

    @PostMapping("/saveRoleMenu")
    public Res saveRoleMenu(@RequestBody RoleDTO roleDTO) {
        roleService.saveRoleMenu(roleDTO.getId(), roleDTO.getMenus());
        return new Res(null);
    }

    @PostMapping("/saveRoleResource")
    public Res saveRoleResource(@RequestBody RoleDTO roleDTO) {
        roleService.saveRoleResource(roleDTO.getId(), roleDTO.getResources());
        return new Res(null);
    }

    @RequestMapping("/refreshCache")
    public Res refreshCache() {
        menuService.putCache();
        securityMetadataSourceService.initMetadataSource();
        return new Res(null);
    }

}
